<template>
    <div>
       <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
            <el-form-item label="用户名" prop="username">
                <el-input v-model="ruleForm.username"></el-input>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="ruleForm.password"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm('ruleForm')">登录</el-button>
            </el-form-item>
       </el-form>
    </div>
</template>

<script>
export default {
    data(){
        return {
            rules:{
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
                ]
            },
            ruleForm:{
                username:'',
                password:''
            }
        }
    },
    methods:{
        submitForm(){
            this.$refs.ruleForm.validate((valid) => {
                if (valid) {
                    let {username,password} = this.ruleForm;
                    //调登录的接口
                    this.$http.post('/api/login',{username,password}).then(res => {
                        if(res.data.code === 1){
                            console.log("====")
                            localStorage.setItem('token',res.data.token);
                            localStorage.setItem('role_id',res.data.role_id);
                            localStorage.setItem('username',username);
                            //登录成功
                            this.$message({
                                message: '恭喜你，登录成功',
                                type: 'success',
                                onClose:()=>{
                                    this.$router.push('/main');
                                }
                            });
                            
                        }else{
                            //登录失败
                            this.$message.error('登录失败');
                        }
                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        }
    }
}
</script>